"use client"
import { useState } from 'react'
import { useRouter } from 'next/navigation'

export default function ReactFormPage() {
    const [title, setTitle] = useState("");
    const [price, setPrice] = useState(0);
    const [description, setDescription] = useState("");
    const [loading, setLoading] = useState(false);
    const router = useRouter();

    const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        setLoading(true);
        try {
            const response = await fetch('react-form/api', {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ title, price, description })
            });
            if (response.ok) {
                router.push("/products-db");
            }
        } catch (error) {
            console.error("Error:", error);
        } finally {
            setLoading(false);
        }
    };

    return (
        <form onSubmit={handleSubmit}>
            <h1 className="text-3xl text-center font-bold">React Form Page</h1>
            <div className="max-w-md mx-auto p-4">
                <label className="block mb-2">
                    Title:
                    <input
                        type="text" className="w-full p-2 border rounded"
                        onChange={(e) => setTitle(e.target.value)}
                    />
                </label>
                <label className="block mb-2">
                    Price:
                    <input
                        type="number" className="w-full p-2 border rounded"
                        onChange={(e) => setPrice(parseInt(e.target.value))}
                    />
                </label>
                <label className="block mb-2">
                    Description:
                    <textarea className="w-full p-2 border rounded" onChange={(e) => setDescription(e.target.value)}></textarea>
                </label>
                <button type="submit" className="bg-blue-500 text-white px-4 py-2 rounded disabled:bg-gray-400" disabled={loading}>
                    {loading ? "Submitting..." : "Submit"}
                </button>
            </div>
        </form>
    )
}
